package com.linkhub.oms.admin.modules.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.google.common.collect.Lists;
import com.linkhub.oms.admin.common.exception.ExceptionFactory;
import com.linkhub.oms.admin.common.util.I18nMessageUtil;
import com.linkhub.oms.admin.modules.product.domain.param.*;
import com.linkhub.oms.admin.modules.product.domain.vo.LocalProductDetailsVO;
import com.linkhub.oms.admin.modules.product.domain.vo.LocalProductSearchVO;
import com.linkhub.oms.admin.modules.product.domain.vo.LocalProductUploadPic;
import com.linkhub.oms.admin.modules.product.service.LocalProductBizService;
import com.linkhub.oms.admin.modules.satoken.session.LhSessionContext;
import com.linkhub.oms.admin.modules.supplier.domain.vo.SupplierVO;
import com.linkhub.oms.common.constant.RoleConstant;
import com.linkhub.oms.common.constant.WmsInfoConstant;
import com.linkhub.oms.common.enums.IEnumConvert;
import com.linkhub.oms.common.enums.mp.LocalProductTypeEnum;
import com.linkhub.oms.common.enums.product.*;
import com.linkhub.oms.common.exception.BizException;
import com.linkhub.oms.common.response.PageDTO;
import com.linkhub.oms.common.util.*;
import com.linkhub.oms.component.mp.util.QtMpUpdateAssist;
import com.linkhub.oms.component.mp.util.QtMybatisPlusUtil;
import com.linkhub.oms.component.redis.locker.DistributedLocker;
import com.linkhub.oms.dao.mapper.LocalProductEntityMapper;
import com.linkhub.oms.dao.mpservice.*;
import com.linkhub.oms.data.sync.api.wms.domain.dto.WmsSyncProductDTO;
import com.linkhub.oms.data.sync.api.wms.domain.response.SyncProductResponse;
import com.linkhub.oms.data.sync.service.impl.WMSApiServiceImpl;
import com.linkhub.oms.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: LocalProductBizService
 * @Author: echo
 * @Date: 2024/3/28 15:59
 * @Version: 1.0
 */
@Slf4j
@Service
public class LocalProductBizServiceImpl implements LocalProductBizService {

    @Resource
    private ILocalProductService localProductService;

    @Resource
    private ILocalProductSupplierService localProductSupplierService;

    @Resource
    private ILocalProductCombinationInfoService localProductCombinationInfoService;

    @Resource
    private ILocalProductAmountDeclaresInfoEntityService localProductAmountDeclaresInfoEntityService;

    @Resource
    private LocalProductEntityMapper localProductEntityMapper;

    @Resource
    private ILocalProductSysBarCodeService localProductSysBarCodeService;

    @Resource
    private ISupplierService supplierService;

    @Resource
    private DistributedLocker distributedLocker;

    @Resource
    private WMSApiServiceImpl wmsApiService;

    @Override
    public PageDTO<LocalProductSearchVO> pageSearchLocalProducts( LocalProductQueryParam queryParam ) {
        String userId = queryParam.getUserId();
        String sku = queryParam.getSku();
        String spu = queryParam.getSpu();
        String productEnTitle = queryParam.getProductEnTitle();
        List<Integer> productType = queryParam.getProductType();
        Integer isRecordStock = queryParam.getIsRecordStock();
        List<String> merchantUserIds = queryParam.getMerchantUserIds();

        List<String> userRoles = LhSessionContext.getUserRoles();

        boolean isEmployee = userRoles.stream().anyMatch(s -> RoleConstant.EMPLOYEE.equals(s) || RoleConstant.STORE_STAFF.equals(s));
        boolean hasSku = StringUtils.isNotBlank(sku);
        boolean hasSpu = StringUtils.isNotBlank(spu);
        boolean hasProductEnTitle = StringUtils.isNotBlank(productEnTitle);

        MPJLambdaWrapper<LocalProductEntity> lambdaWrapper = JoinWrappers.lambda(LocalProductEntity.class);
        lambdaWrapper.select(LocalProductEntity::getSkuId,
                        LocalProductEntity::getSku,
                        LocalProductEntity::getSpu,
                        LocalProductEntity::getProductEnTitle,
                        LocalProductEntity::getImgUrl,
                        LocalProductEntity::getProductType,
                        LocalProductEntity::getCreatedTime)
                .selectAs(UserEntity::getUserId, LocalProductSearchVO::getMerchantUserId)
                .selectAs(UserEntity::getUserName, LocalProductSearchVO::getMerchantUserName)
                .in(LocalProductEntity::getProductType, productType)
                .eq(StringUtils.isNotBlank(userId) && !isEmployee, LocalProductEntity::getUserId, userId)
                .eq(isRecordStock != null, LocalProductEntity::getIsRecordStock, isRecordStock)
                .like(hasSku, LocalProductEntity::getSku, sku)
                .like(hasSpu, LocalProductEntity::getSpu, spu)
                .like(hasProductEnTitle, LocalProductEntity::getProductEnTitle, productEnTitle)
                .leftJoin(UserEntity.class, on -> on.eq(UserEntity::getUserId, LocalProductEntity::getUserId));

        if (CollectionUtils.isNotEmpty(merchantUserIds)) {
            lambdaWrapper.in(UserEntity::getUserId, merchantUserIds);
        }
        lambdaWrapper.orderByDesc(LocalProductEntity::getUpdateTime).page(new Page<>(queryParam.getPage(), queryParam.getSize()));

        Page<LocalProductSearchVO> objectPage = new Page<>(queryParam.getPage(), queryParam.getSize());
        objectPage.setOptimizeJoinOfCountSql(false);
        Page<LocalProductSearchVO> page = localProductEntityMapper.selectJoinPage(objectPage, LocalProductSearchVO.class, lambdaWrapper);

        return QtMybatisPlusUtil.convertPage(page, this::convert);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveLocalProduct( LocalProductAddParam localProductAddParam ) {
        saveCheckCodeIsExist(localProductAddParam);

        LocalProductEntity localProductEntity = checkAndConvert(localProductAddParam);

        // 本地产品同步到WMS
        WmsSyncProductDTO wmsSyncProductDTO = createWmsSyncProductDTO(localProductAddParam, localProductEntity);
        final SyncProductResponse syncProductResponse = wmsApiService.syncAddProduct(wmsSyncProductDTO);
        if (!syncProductResponse.success()) {
            // 同步产品信息到仓库失败直接返回
            throw new BizException(I18nMessageUtil.getMessage("local.product.sync.wms.failed", syncProductResponse.getResponse().getMessage()));
        }

        localProductEntity.setItemId(syncProductResponse.getResponse().getItemId());
        localProductService.save(localProductEntity);

        // 保存商品供应商记录
        List<String> sysSupplierIdList = localProductAddParam.getSysSupplierIdList();
        saveSysSupplierIdList(localProductAddParam.getUserId(), localProductEntity.getSkuId(), sysSupplierIdList);

        List<SingleProductInfo> singleProductInfos = localProductAddParam.getSingleProductInfos();
        // 保存组合产品单个产品信息
        saveSingleProductInfos(localProductAddParam.getUserId(), localProductEntity.getSkuId(), singleProductInfos);

        List<AmountDeclares> amountDeclares = localProductAddParam.getAmountDeclares();
        // 保存本地产品申报金额详情信息
        saveAmountDeclares(localProductAddParam.getUserId(), localProductEntity.getSkuId(), amountDeclares);

    }

    private String getSysBarCode( String userId, String skuId ) {
        // 使用数据库的自增ID作为系统商品条码
        localProductSysBarCodeService.insertByUserIdAndSkuId(userId, skuId);
        LocalProductSysBarCodeEntity localProductSysBarCodeEntity = localProductSysBarCodeService.queryLocalProductBarCode(userId, skuId);
        Long id = localProductSysBarCodeEntity.getId();
        return String.format("BC%010d", id);
    }

    @Override
    public List<LocalProductSearchVO> queryLocalProductBySupplierId( SupplierQueryLocalProductParam supplierQueryLocalProductParam ) {
        String sysSupplierId = supplierQueryLocalProductParam.getSysSupplierId();
        Boolean isRecordStock = supplierQueryLocalProductParam.getIsRecordStock();
        List<LocalProductEntity> list = localProductSupplierService.queryLocalProductsBySupplierId(sysSupplierId, isRecordStock);
        return QtBeanUtil.copyList(list, LocalProductSearchVO::new);
    }

    /**
     * @param skuId
     * @return
     */
    @Override
    public LocalProductDetailsVO localProductsDetails( String skuId ) {
        LocalProductEntity localProduct = localProductService.getBySkuId(skuId);
        if (Objects.isNull(localProduct)) {
            throw ExceptionFactory.getI18nBizException("local.product.not.exist");
        }
        LocalProductDetailsVO localProductDetailsVO = convert(localProduct);

        // 查找并设置商品供应商信息
        List<LocalProductSupplierEntity> localProductSupplierEntityList = localProductSupplierService.querySysSupplierIdBySkuId(localProductDetailsVO.getMerchantUserId(), skuId);
        if (CollectionUtils.isNotEmpty(localProductSupplierEntityList)) {
            List<String> sysSupplierIdList = QtStreamUtil.map(localProductSupplierEntityList, LocalProductSupplierEntity::getSysSupplierId);
            List<SupplierEntity> supplierEntityList = supplierService.getBySupplierIds(localProductDetailsVO.getMerchantUserId(), sysSupplierIdList);
            localProductDetailsVO.setSupplierList(QtBeanUtil.copyList(supplierEntityList, SupplierVO::new));
        }

        // 查找并设置申报金额配置
        List<LocalProductAmountDeclaresInfoEntity> localProductAmountDeclaresInfoEntityList = localProductAmountDeclaresInfoEntityService
                .queryAmountDeclaresInfoBySkuId(localProductDetailsVO.getMerchantUserId(), skuId);
        localProductDetailsVO.setAmountDeclares(QtBeanUtil.copyList(localProductAmountDeclaresInfoEntityList, AmountDeclares::new));

        // 查找并设置组合产品对应的单个产品信息
        LocalProductTypeEnum localProductTypeEnum = IEnumConvert.valueOf(localProduct.getProductType(), LocalProductTypeEnum.class);
        if (localProductTypeEnum == LocalProductTypeEnum.COMPOSITE_PRODUCT) {

            List<LocalProductCombinationInfoEntity> localProductCombinationInfoEntityList = localProductCombinationInfoService
                    .queryCombinationInfoBySkuId(localProductDetailsVO.getMerchantUserId(), skuId);
            if (CollectionUtils.isNotEmpty(localProductCombinationInfoEntityList)) {
                // 查出所有单个skuID
                List<String> singleSkuId = QtStreamUtil.map(localProductCombinationInfoEntityList, LocalProductCombinationInfoEntity::getSingleSkuId);
                // 获取到单个skuID对应的产品信息
                List<LocalProductEntity> localProductEntities = localProductService.listBySkuIds(singleSkuId);
                // 获取到单个skuId对应的数量
                Map<String, Integer> skuIdToNumsMap = localProductCombinationInfoEntityList.stream()
                        .collect(Collectors.toMap(LocalProductCombinationInfoEntity::getSingleSkuId, LocalProductCombinationInfoEntity::getSingleSkuNums));
                // 转化为SingleProductInfos
                List<SingleProductInfo> singleProductInfos = localProductEntities.stream()
                        .map(productEntity -> {
                            SingleProductInfo singleProductInfo = new SingleProductInfo();
                            QtBeanUtil.copyProperties(productEntity, singleProductInfo);
                            singleProductInfo.setNums(skuIdToNumsMap.getOrDefault(productEntity.getSkuId(), 0));
                            return singleProductInfo;
                        })
                        .collect(Collectors.toList());
                localProductDetailsVO.setSingleProductInfos(singleProductInfos);
            }
        }

        return localProductDetailsVO;
    }

    /**
     * @param userId
     * @param skuId
     * @param picFile
     * @return
     */
    @Override
    public LocalProductUploadPic uploadPic( String userId, String skuId, MultipartFile picFile ) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editLocalProduct( String skuId, LocalProductEditParam localProductEditParam ) {
        editCheckCodeIsExist(skuId, localProductEditParam);
        String merchantUserId = localProductEditParam.getMerchantUserId();

        // 加锁
        String lockKey = CacheKeyAssist.getLocalProductEditLockKey(merchantUserId, skuId);
        if (!distributedLocker.tryLock(lockKey)) {
            throw ExceptionFactory.getI18nBizException("local.product.edit.problem");
        }
        try {
            LocalProductEntity localProductEntity = checkAndConvert(skuId, localProductEditParam);

            // 本地产品更新到WMS
            WmsSyncProductDTO wmsSyncProductDTO = createWmsSyncProductDTO(localProductEditParam, localProductEntity);
            final SyncProductResponse syncProductResponse = wmsApiService.syncUpdateProduct(wmsSyncProductDTO);
            if (!syncProductResponse.success()) {
                // 同步产品信息到仓库失败直接返回
                throw new BizException(I18nMessageUtil.getMessage("local.product.sync.wms.failed", syncProductResponse.getResponse().getMessage()));
            }

            localProductService.updateBySkuId(localProductEntity);

            String userId = localProductEditParam.getUserId();

            // 删除原商品供应商记录
            localProductSupplierService.removeByUserIdAndSkuId(merchantUserId, skuId);
            // 保存商品供应商记录
            List<String> sysSupplierIdList = localProductEditParam.getSysSupplierIdList();
            saveSysSupplierIdList(merchantUserId, skuId, sysSupplierIdList);

//            组合产品单个信息不允许编辑
//            // 删除组合产品单个信息
//            localProductCombinationInfoService.deleteLocalProductCombinationInfo(userId, skuId);
//            // 保存组合产品单个产品信息
//            List<SingleProductInfo> singleProductInfos = localProductEditParam.getSingleProductInfos();
//            saveSingleProductInfos(userId, skuId, singleProductInfos);

            // 删除本地产品申报金额详情信息
            localProductAmountDeclaresInfoEntityService.deleteLocalProductAmountDeclaresInfo(userId, skuId);
            List<AmountDeclares> amountDeclares = localProductEditParam.getAmountDeclares();
            // 保存本地产品申报金额详情信息
            saveAmountDeclares(userId, skuId, amountDeclares);
        }finally {
            distributedLocker.unlock(lockKey);
        }
    }

    @Override
    public void localProductRecheck( String skuId, LocalProductRecheckParam localProductRecheckParam ) {
        LocalProductEntity localProductEntity = new LocalProductEntity();
        BeanUtil.copyProperties(localProductRecheckParam, localProductEntity);
        localProductEntity.setSkuId(skuId);
        localProductEntity.setUserId(localProductRecheckParam.getMerchantUserId());
        localProductEntity.setStoreUserId(localProductRecheckParam.getUserId());
        // 加锁
        String lockKey = CacheKeyAssist.getLocalProductEditLockKey(localProductRecheckParam.getMerchantUserId(), skuId);
        if (!distributedLocker.tryLock(lockKey)) {
            throw ExceptionFactory.getI18nBizException("local.product.edit.problem");
        }
        try {
            localProductService.updateLocalProductBySkuId(localProductEntity);
        }finally {
            distributedLocker.unlock(lockKey);
        }

    }

    private void saveSysSupplierIdList( String userId, String skuId, List<String> sysSupplierIdList ) {
        if (CollectionUtils.isNotEmpty(sysSupplierIdList)) {
            for (String sysSupplierId : sysSupplierIdList) {
                if (StringUtils.isNotBlank(sysSupplierId)) {
                    LocalProductSupplierEntity localProductSupplierEntity = new LocalProductSupplierEntity();
                    localProductSupplierEntity.setUserId(userId);
                    localProductSupplierEntity.setSkuId(skuId);
                    localProductSupplierEntity.setSysSupplierId(sysSupplierId);
                    localProductSupplierEntity.setCreatedTime(LocalDateTime.now());
                    localProductSupplierEntity.setUpdateTime(LocalDateTime.now());

                    localProductSupplierService.save(localProductSupplierEntity);
                }
            }
        }
    }

    private void saveSingleProductInfos( String userId, String skuId, List<SingleProductInfo> singleProductInfos ) {
        if (CollectionUtils.isNotEmpty(singleProductInfos)) {
            List<LocalProductCombinationInfoEntity> localProductCombinationInfoEntities = new ArrayList<>();
            for (SingleProductInfo singleProductInfo : singleProductInfos) {
                LocalProductCombinationInfoEntity localProductCombinationInfoEntity = new LocalProductCombinationInfoEntity();
                localProductCombinationInfoEntity.setUserId(userId);
                localProductCombinationInfoEntity.setSkuId(skuId);
                localProductCombinationInfoEntity.setSingleSkuId(singleProductInfo.getSkuId());
                localProductCombinationInfoEntity.setSingleSkuNums(singleProductInfo.getNums());
                localProductCombinationInfoEntity.setCreatedTime(LocalDateTime.now());
                localProductCombinationInfoEntity.setUpdateTime(LocalDateTime.now());
                localProductCombinationInfoEntities.add(localProductCombinationInfoEntity);
            }
            localProductCombinationInfoService.saveLocalProductCombinationInfo(localProductCombinationInfoEntities);
        }
    }

    private void saveAmountDeclares( String userId, String skuId, List<AmountDeclares> amountDeclares ) {
        if (CollectionUtils.isNotEmpty(amountDeclares)) {
            List<LocalProductAmountDeclaresInfoEntity> localProductAmountDeclaresInfoEntities = new ArrayList<>();
            for (AmountDeclares amountDeclare : amountDeclares) {
                LocalProductAmountDeclaresInfoEntity localProductAmountDeclaresInfoEntity = new LocalProductAmountDeclaresInfoEntity();
                QtBeanUtil.copyProperties(amountDeclare, localProductAmountDeclaresInfoEntity);
                localProductAmountDeclaresInfoEntity.setUserId(userId);
                localProductAmountDeclaresInfoEntity.setSkuId(skuId);
                localProductAmountDeclaresInfoEntity.setCreatedTime(LocalDateTime.now());
                localProductAmountDeclaresInfoEntity.setUpdateTime(LocalDateTime.now());
                localProductAmountDeclaresInfoEntities.add(localProductAmountDeclaresInfoEntity);
            }
            localProductAmountDeclaresInfoEntityService.saveLocalProductAmountDeclaresInfo(localProductAmountDeclaresInfoEntities);
        }
    }

    private void editCheckCodeIsExist( String skuId, LocalProductEditParam localProductEditParam ) {
        checkCodeIsExist(skuId, localProductEditParam.getMerchantUserId(), localProductEditParam.getSku(), localProductEditParam.getUpc(), localProductEditParam.getFnsku(), localProductEditParam.getOtherCode());
    }

    private void saveCheckCodeIsExist( LocalProductAddParam localProductAddParam ) {
        checkCodeIsExist(null, localProductAddParam.getUserId(), localProductAddParam.getSku(), localProductAddParam.getUpc(), localProductAddParam.getFnsku(), localProductAddParam.getOtherCode());
    }

    private void checkCodeIsExist( String skuId, String userId, String sku, String upc, String fnsku, String otherCode ) {
        if (StringUtils.isNotBlank(userId)) {
            LocalProductEntity localProductEntity = null;
            if (StringUtils.isNotBlank(sku)) {
                localProductEntity = localProductService.getLocalProductBySku(skuId, userId, sku);
                if (!Objects.isNull(localProductEntity)) {
                    throw new BizException(I18nMessageUtil.getMessage("local.product.sku.exist", sku));
                }
            }
            if (StringUtils.isNotBlank(upc)) {
                localProductEntity = localProductService.getLocalProductByUpc(skuId, userId, upc);
                if (!Objects.isNull(localProductEntity)) {
                    throw new BizException(I18nMessageUtil.getMessage("local.product.upc.exist", upc, localProductEntity.getSku()));
                }
            }
            if (StringUtils.isNotBlank(fnsku)) {
                localProductEntity = localProductService.getLocalProductByFnsku(skuId, userId, fnsku);
                if (!Objects.isNull(localProductEntity)) {
                    throw new BizException(I18nMessageUtil.getMessage("local.product.fnsku.exist", fnsku, localProductEntity.getSku()));
                }
            }
            if (StringUtils.isNotBlank(otherCode)) {
                localProductEntity = localProductService.getLocalProductByOtherCode(skuId, userId, otherCode);
                if (!Objects.isNull(localProductEntity)) {
                    throw new BizException(I18nMessageUtil.getMessage("local.product.otherCode.exist", otherCode, localProductEntity.getSku()));
                }
            }
        }
    }

    private LocalProductDetailsVO convert( LocalProductEntity localProductEntity ) {

        LocalProductDetailsVO vo = new LocalProductDetailsVO();
        BeanUtil.copyProperties(localProductEntity, vo);
        vo.setLogisticsAttributeList(localProductEntity.getLogisticsAttribute());

        // 组装本地商品复核信息
        vo.setLocalProductRecheckVo(new LocalProductDetailsVO.LocalProductRecheckVo());
        BeanUtil.copyProperties(localProductEntity, vo.getLocalProductRecheckVo());

        String defaultPackingMaterial = localProductEntity.getDefaultPackingMaterial();
        vo.setDefaultPackingMaterialSkuId(defaultPackingMaterial);
        if (StringUtils.isNotBlank(defaultPackingMaterial)) {
            LocalProductEntity localProductDefaultPackingMaterial = localProductService.getBySkuId(defaultPackingMaterial);
            if (!Objects.isNull(localProductDefaultPackingMaterial)) {
                vo.setDefaultPackingMaterialSku(localProductDefaultPackingMaterial.getSku());
            }
        }
        vo.setMerchantUserId(localProductEntity.getUserId());
        return vo;
    }

    private LocalProductSearchVO convert( LocalProductSearchVO localProductSearchVO ) {
        LocalProductSearchVO vo = new LocalProductSearchVO();
        BeanUtil.copyProperties(localProductSearchVO, vo);
        return vo;
    }

    private LocalProductEntity checkAndConvert( String skuId, LocalProductEditParam localProductEditParam ) {
        List<Integer> localProductLogisticsAttributeEnumList = Arrays.stream(LocalProductLogisticsAttributeEnum.values()).map(LocalProductLogisticsAttributeEnum::getCode).collect(Collectors.toList());
        if (!localProductLogisticsAttributeEnumList.containsAll(localProductEditParam.getLogisticsAttributeList())) {
            throw ExceptionFactory.getI18nBizException("llocal.product.logistics.attribute.not.exist");
        }
        List<Integer> localProductWrapTypeEnumList = Arrays.stream(LocalProductWrapTypeEnum.values()).map(LocalProductWrapTypeEnum::getCode).collect(Collectors.toList());
        if (localProductEditParam.getWrapType() != null && !localProductWrapTypeEnumList.contains(localProductEditParam.getWrapType())) {
            throw ExceptionFactory.getI18nBizException("local.product.wrap.type.not.exist");
        }

//        List<AmountDeclares> amountDeclares = localProductEditParam.getAmountDeclares();
//        if (amountDeclares == null || amountDeclares.isEmpty()) {
//            // 至少需要设置一个国家的申报金额
//            throw ExceptionFactory.getI18nBizException("local.product.amount.declares.num.limit");
//        }

        String categoryCode = localProductEditParam.getCategoryCode();
        List<String> localProductCategoryEnumCodeList = Arrays.stream(LocalProductCategoryEnum.values()).map(LocalProductCategoryEnum::getCode).collect(Collectors.toList());
        LocalProductEntity entity = new LocalProductEntity();
        BeanUtil.copyProperties(localProductEditParam, entity);
        if (StringUtils.isNotBlank(categoryCode)) {
            if (localProductCategoryEnumCodeList.contains(categoryCode)) {
                entity.setCategoryName(IEnumConvert.valueOf(categoryCode, LocalProductCategoryEnum.class).getEnName());
            } else {
                throw ExceptionFactory.getI18nBizException("local.product.category.code.not.exist");
            }
        }

        // 获取到产品系统条码，更新产品到WMS时需要用到
        entity.setSysBarCode(localProductService.getBySkuId(skuId).getSysBarCode());

        entity.setWrapType(QtMpUpdateAssist.acquireIntegerIfNull(localProductEditParam.getWrapType()));
        entity.setUserId(localProductEditParam.getMerchantUserId());
        List<Integer> logisticsAttributeList = QtOptionalUtil.of(localProductEditParam.getLogisticsAttributeList()).orElse(Lists.newArrayListWithCapacity(0));
        entity.setLogisticsAttribute(logisticsAttributeList);

        entity.setSkuId(skuId);
        entity.setDefaultPackingMaterial(localProductEditParam.getDefaultPackingMaterialSkuId());
        entity.setUpdateTime(LocalDateTime.now());

        return entity;
    }

    private LocalProductEntity checkAndConvert( LocalProductAddParam productAddParam ) {

        List<Integer> localProductLogisticsAttributeEnumList = Arrays.stream(LocalProductLogisticsAttributeEnum.values()).map(LocalProductLogisticsAttributeEnum::getCode).collect(Collectors.toList());
        if (!localProductLogisticsAttributeEnumList.containsAll(productAddParam.getLogisticsAttributeList())) {
            throw ExceptionFactory.getI18nBizException("llocal.product.logistics.attribute.not.exist");
        }
        List<Integer> localProductWrapTypeEnumList = Arrays.stream(LocalProductWrapTypeEnum.values()).map(LocalProductWrapTypeEnum::getCode).collect(Collectors.toList());
        if (productAddParam.getWrapType() != null && !localProductWrapTypeEnumList.contains(productAddParam.getWrapType())) {
            throw ExceptionFactory.getI18nBizException("local.product.wrap.type.not.exist");
        }

//        List<AmountDeclares> amountDeclares = productAddParam.getAmountDeclares();
//        if (amountDeclares == null || amountDeclares.isEmpty()) {
//            // 至少需要设置一个国家的申报金额
//            throw ExceptionFactory.getI18nBizException("local.product.amount.declares.num.limit");
//        }


        String categoryCode = productAddParam.getCategoryCode();
        List<String> localProductCategoryEnumCodeList = Arrays.stream(LocalProductCategoryEnum.values()).map(LocalProductCategoryEnum::getCode).collect(Collectors.toList());
        LocalProductEntity entity = new LocalProductEntity();
        BeanUtil.copyProperties(productAddParam, entity);

        if (StringUtils.isNotBlank(categoryCode)) {
            if (localProductCategoryEnumCodeList.contains(categoryCode)) {
                entity.setCategoryName(IEnumConvert.valueOf(categoryCode, LocalProductCategoryEnum.class).getEnName());
            } else {
                throw ExceptionFactory.getI18nBizException("local.product.category.code.not.exist");
            }
        }

        LocalProductTypeEnum localProductTypeEnum = IEnumConvert.valueOf(productAddParam.getProductType(), LocalProductTypeEnum.class);
        if (localProductTypeEnum == LocalProductTypeEnum.PACKAGING_MATERIAL) {
            // 本地包材包材类型为必填
            LocalProductPackingMaterialTypeEnum localProductPackingMaterialTypeEnum = IEnumConvert.valueOf(productAddParam.getPackingMaterialType(), LocalProductPackingMaterialTypeEnum.class);
            if (localProductPackingMaterialTypeEnum != null) {
                entity.setIsRecordStock(localProductPackingMaterialTypeEnum.getIsRecordStock());
            } else {
                throw ExceptionFactory.getI18nBizException("local.product.packing.material.type.not.exist");
            }
        } else if (localProductTypeEnum == LocalProductTypeEnum.COMPOSITE_PRODUCT) {
            // 组合产品的SingleProductInfo参数为必填且不能只含一个产品
            List<SingleProductInfo> singleProductInfos = productAddParam.getSingleProductInfos();
            if (singleProductInfos == null || singleProductInfos.isEmpty() || singleProductInfos.stream().mapToInt(SingleProductInfo::getNums).sum() <= 1) {
                throw ExceptionFactory.getI18nBizException("local.product.packing.combo.num.limit");
            }
        }

        String skuId = IdUtil.getSnowflake().nextIdStr();
        entity.setSkuId(skuId);

        // 获取并设置系统商品条码
        entity.setSysBarCode(getSysBarCode(productAddParam.getUserId(), skuId));

        List<Integer> logisticsAttributeList = QtOptionalUtil.of(productAddParam.getLogisticsAttributeList()).orElse(Lists.newArrayListWithCapacity(0));
        entity.setLogisticsAttribute(logisticsAttributeList);
        entity.setDefaultPackingMaterial(productAddParam.getDefaultPackingMaterialSkuId());
        entity.setCreatedTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());

        return entity;
    }

    private WmsSyncProductDTO createWmsSyncProductDTO( LocalProductBaseParam localProductParam, LocalProductEntity localProductEntity ) {
        WmsSyncProductDTO wmsSyncProductDTO = new WmsSyncProductDTO();
        wmsSyncProductDTO.setOwnerCode(WmsInfoConstant.OWNER_CODE);
        wmsSyncProductDTO.setWarehouseCode(WmsInfoConstant.WAREHOUSE_CODE);
        wmsSyncProductDTO.setSupplierCode(String.join(",", localProductParam.getSysSupplierIdList()));
        // 获取到所有供应商名称并用 , 连接
        if (localProductParam.getSysSupplierIdList() != null && !localProductParam.getSysSupplierIdList().isEmpty()) {
            wmsSyncProductDTO.setSupplierName(supplierService.getBySupplierIds(localProductParam.getUserId(), localProductParam.getSysSupplierIdList()).stream().map(SupplierEntity::getSupplierName).collect(Collectors.joining(",")));
        }

        wmsSyncProductDTO.setItemCode(WmsUtil.createItemCode(localProductParam.getUserId(), localProductEntity.getSkuId()));
        // 新增产品无itemId，编辑产品暂不设置
        // wmsSyncProductDTO.setItemId("itemid0101240613000003");
        wmsSyncProductDTO.setItemName(localProductParam.getSku());

//        LocalProductTypeEnum localProductTypeEnum = IEnumConvert.valueOf(localProductParam.getProductType(), LocalProductTypeEnum.class);
//        if (LocalProductTypeEnum.PACKAGING_MATERIAL.equals(localProductTypeEnum)) {
//            wmsSyncProductDTO.setItemType(WmsInfoConstant.BC);
//        } else if (LocalProductTypeEnum.COMPOSITE_PRODUCT.equals(localProductTypeEnum)) {
//            wmsSyncProductDTO.setItemType(WmsInfoConstant.ZH);
//        } else {
//            wmsSyncProductDTO.setItemType(WmsInfoConstant.ZC);
//        }
        wmsSyncProductDTO.setItemType(WmsInfoConstant.OTHER);

        String categoryName = WmsInfoConstant.SYNC_PRODUCT_DEFAULT_CATEGORY_NAME;
        if (localProductEntity.getCategoryName() != null && !localProductEntity.getCategoryName().isEmpty()) {
            categoryName = localProductEntity.getCategoryName();
        } else if (localProductEntity.getPackingMaterialType() != null) {
            LocalProductMaterialTypeEnum localProductMaterialTypeEnum = IEnumConvert.valueOf(localProductEntity.getPackingMaterialType(), LocalProductMaterialTypeEnum.class);
            if (localProductMaterialTypeEnum != null) {
                categoryName = localProductMaterialTypeEnum.getEnName();
            }
        }
        wmsSyncProductDTO.setCategoryName(categoryName);

        wmsSyncProductDTO.setShortName(localProductParam.getSpu());
        wmsSyncProductDTO.setEnglishName(localProductParam.getProductEnTitle());
        wmsSyncProductDTO.setBarCode(WmsUtil.createBarCode(localProductEntity.getSysBarCode(), localProductParam.getUpc(), localProductParam.getFnsku(), localProductParam.getOtherCode()));
        wmsSyncProductDTO.setBrandName(localProductParam.getBrand());
        wmsSyncProductDTO.setSkuProperty(WmsUtil.createSkuProperty(localProductParam.getLogisticsAttributeList()));

        // 长宽高重量不准确，暂时不设置
        // wmsSyncProductDTO.setLength("10");
        // wmsSyncProductDTO.setWidth("50");
        // wmsSyncProductDTO.setHeight("100");
        // wmsSyncProductDTO.setGrossWeight("10");
        wmsSyncProductDTO.setPurchasePrice(localProductParam.getPurchasePrice());
        wmsSyncProductDTO.setPackCode(localProductEntity.getDefaultPackingMaterial());
        return wmsSyncProductDTO;
    }
}
